<template>
  <page-meta :root-font-size="globalData.fontsize + 'px'" user-scalable="no" viewport-fit="cover" style="display: block"></page-meta>
  <view class="h100p">
    <view :style="globalData.appStyle.navStyle">
      <uni-nav-bar left-icon="left" @clickLeft="navigateBackPage" :height="globalData.navBarInfo.height" fixed backgroundColor="#FF7C00" :border="false" color="#fff">
        <view class="inputView flca search_header" @click="jumpToPage(`/pages/global/search-page/category-search/index?searchMode=${searchMode}`)">
          <uni-icons type="search" size="21" class="icon_search"></uni-icons>
          <input type="text" class="input" v-model="keyWords" placeholder="请输入搜索分类" />
        </view>
      </uni-nav-bar>
    </view>
    <view :style="globalData.appStyle.contentStyle">
      <view class="categories" :style="formContentStyle">
        <scroll-view :class="{ primary: true, h650: selectedList.length > 0 }" scroll-y>
          <view v-for="(item, index) in categoryList" :key="item" class="item" :class="{ active: item.id === curItem.id }" @click="categoryItemClick(item)">
            <text class="name"> {{ item.categoryName }} </text>
          </view>
        </scroll-view>
        <scroll-view :class="{ secondary: true, h650: selectedList.length > 0 }" scroll-y>
          <view v-for="item in categoryChilds" :key="item" class="item" hover-class="none" @click="selectChild(item)">
            <text :class="['name', selectedList.some(el => el.categoryName === item.categoryName) ? 'active-color' : '']"> {{ item.categoryName }} </text>
          </view>
        </scroll-view>
      </view>
      <FixedBottomBtnCustom v-if="selectedList.length > 0">
        <view class="eidt_bottom_btn_selected">
          <view class="flb">
            <text>
              <text style="font-weight: 600; padding-right: 10rem">我选择的分类</text>
              <text style="font-size: 14rem; font-weight: 400; color: #a6a6a6">(点击即可删除)</text>
            </text>
            <text style="font-size: 14rem; font-weight: 400; color: #a6a6a6">{{ selectedList.length }}/{{ searchMode === 1 ? 5 : 1 }}</text>
          </view>
          <view class="uni-tag-style">
            <view v-for="(tag, key) in selectedList" class="inner-tag" :key="key" @click="closeTag(key)">
              {{ tag.categoryName }}
            </view>
          </view>
          <view class="eidt_bottom_btn flca">
            <view class="inner-btn inner-btn-clear" @click="clearData()">清除</view>
            <view class="inner-btn ml20" @click="jumpToDetail()">确定选择</view>
          </view>
        </view>
      </FixedBottomBtnCustom>
    </view>
  </view>
</template>
<script>
const api = require('@/utils/request.js');
import commonMxins from '@/mixins/common.js';
import FixedBottomBtnCustom from '@/component/FixedBottomBtnCustom.vue';
export default {
  mixins: [commonMxins],
  component: {
    FixedBottomBtnCustom
  },
  data() {
    return {
      // 筛选功能，多个类别选择-1  单个类别选择-2
      searchMode: 1,
      selectedList: [],
      categoryList: [],
      categoryChilds: [],
      curItem: {},
      keyWords: '',
      formContentStyle: '',
      eventChannel: ''
    };
  },
  onLoad(options) {
    this.searchMode = Number(options?.searchMode ?? 1);
    this.eventChannel = this.getOpenerEventChannel();
    this.getAllCategory();
    // 逻辑操作，数据回显
    if (options.newSource == 1) {
      this.reShowData();
    } else {
      this.commSetStory('remove');
    }
  },
  watch: {
    'selectedList.length': function (newLength, oldLength) {
      console.log('数组长度变化了:', newLength);
      this.formContentStyle = newLength > 0 ? `height: calc(100% - ${this.globalData.customizeInfo.safeAreaBottom + 185}rem)` : `height: calc(100%)`;
    }
  },

  methods: {
    reShowData() {
      const selectCategoryInfo = uni.getStorageSync('reShowCategorySelection') ? JSON.parse(uni.getStorageSync('reShowCategorySelection')) : [];
      this.selectedList = selectCategoryInfo[this.searchMode] ? selectCategoryInfo[this.searchMode] : [];
    },
    jumpToPage(url) {
      uni.navigateTo({
        url,
        events: {
          categroyVHTML: info => {
            this.categroyVHTML(info);
          }
        }
      });
    },
    // 删除已选中的tag
    closeTag(key) {
      this.selectedList.splice(key, 1);
    },
    // 回退
    navigateBackPage() {
      uni.navigateBack({ delta: 1 });
    },
    async getAllCategory() {
      let res = await api.request({ url: '/category/queryAll', data: {}, method: 'GET' });
      this.categoryList = res.data;
      if (res.data.length > 0) {
        this.curItem = this.categoryList[0];
        this.categoryChilds = this.curItem.children;
      }
    },
    search() {},
    // 指定内容搜索回显
    categroyVHTML({ parentId, id }) {
      const parentInfo = this.categoryList.find(el => el.id === parentId);
      this.categoryItemClick(parentInfo);
      const childInfo = this.categoryChilds.find(el => el.id === id);
      this.selectChild(childInfo);
    },
    // 点击页面类别
    categoryItemClick(item) {
      if ((this.searchMode === 1 && this.selectedList.length >= 5) || this.selectedList.some(el => el.categoryName === item.categoryName)) {
        return;
      }
      if (this.searchMode === 2) {
        this.selectedList = [];
      }
      this.curItem = { ...item };
      this.selectedList.push({ categoryName: item.categoryName, parentName: item.categoryName });
      this.$forceUpdate();
      this.categoryChilds = this.curItem.children;
    },
    selectChild(item) {
      if ((this.searchMode === 1 && this.selectedList.length >= 5) || this.selectedList.some(el => el.categoryName === item.categoryName)) {
        return;
      }
      if (this.searchMode === 2) {
        this.selectedList = [];
      }
      this.selectedList.push({ categoryName: item.categoryName, parentName: this.curItem.categoryName });
      this.$forceUpdate();
    },
    clearData() {
      this.selectedList = [];
      this.commSetStory('remove');
    },
    commSetStory(setMode) {
      // 数据回显埋点
      const selectCategoryInfo = uni.getStorageSync('reShowCategorySelection') ? JSON.parse(uni.getStorageSync('reShowCategorySelection')) : [];
      selectCategoryInfo[this.searchMode] = setMode === 'remove' ? [] : this.selectedList;
      uni.setStorageSync('reShowCategorySelection', JSON.stringify(selectCategoryInfo));
    },
    jumpToDetail() {
      this.commSetStory();
      // 检索条件筛选
      if (this.searchMode === 1) {
        uni.navigateBack({
          delta: 1
        });
        this.eventChannel.emit(
          'searchInfo',
          this.selectedList.map(el => el.parentName)
        );
      } else {
        // 做历史类别选择数据存储
        const historyList = uni.getStorageSync('historySelectedCategory');
        const list = historyList ? JSON.parse(historyList) : [];
        const resultList = [...list];
        this.selectedList.forEach(element => {
          if (!list.some(el => el.categoryName == element.categoryName)) {
            resultList.push(element);
          }
        });
        uni.setStorageSync('historySelectedCategory', JSON.stringify(resultList));
        // 数据回传
        // 存储两个字段 数据
        if (this.selectedList.length) {
          const info = this.selectedList[0];
          this.eventChannel.emit('getCategoryInfo', info);
        }
        uni.navigateBack({ delta: 1 });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
